const express = require("express");
const User = require("../models/User");
const auth = require("../middleware/auth");

const router = express.Router();

// 模糊搜索用户（按用户名或邮箱），返回 id/username/email
router.get("/search", auth, async (req, res) => {
  try {
    const q = (req.query.q || "").trim();
    if (!q) {
      return res.status(400).json({ message: "缺少查询参数 q" });
    }
    const regex = new RegExp(q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
    const users = await User.find({
      $or: [{ username: regex }, { email: regex }],
    })
      .select({ username: 1, email: 1 })
      .limit(20)
      .lean();
    return res
      .status(200)
      .json(
        users.map((u) => ({ id: u._id, username: u.username, email: u.email }))
      );
  } catch (err) {
    console.error(err);
    return res.status(500).json({ message: "服务器错误" });
  }
});

module.exports = router;
